﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Net;
using System.Windows.Media.Imaging;
using System.IO;
using System.Text.RegularExpressions;

namespace DailyStrips.Model.ImageProvideStrategies
{
  class WebPageImageProviderStrategy : IImageProviderStrategy 
  {

    private string host;

    public WebPageImageProviderStrategy()
      :this("http://wulffmorgenthaler.dk")
    { }

    public WebPageImageProviderStrategy(string host)
    {
      // TODO: Complete member initialization
      this.host = host;
    }

    public bool IsImageAvailable(DateTime date)
    {
      return true;
    }

    protected ImageSource HandleGetImage(DateTime date)
    {
      string path = string.Format("{0}/{1}/{2}/{3}/",
        host,
        date.Year,
        date.Month.ToString().PadLeft(2, '0'),
        date.Day.ToString().PadLeft(2, '0'));



      WebRequest request = HttpWebRequest.Create(path);
      request.Proxy = HttpWebRequest.GetSystemWebProxy();
      request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

      WebResponse responce = request.GetResponse();

      string str = string.Empty;

      using (StreamReader reader = new StreamReader(responce.GetResponseStream()))
      {
        str = reader.ReadToEnd();
      }

      string imagepath = string.Format("{0}{1}", host, ParseHtml(str));

      request = HttpWebRequest.Create(imagepath);
      request.Proxy = HttpWebRequest.GetSystemWebProxy();
      request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

      responce = request.GetResponse();

      BitmapImage image = new BitmapImage();
      image.BeginInit();
      image.StreamSource = responce.GetResponseStream();
      image.EndInit();

      return image;
    }

    private string ParseHtml(string str)
    {
      Regex regex = new Regex("<div class=\"stribe\">([\t\r\n ])*" +
                                  "<a href=\"(?<href>(.*))\">([\t\r\n ])*" +
                                    "<img src=\"(?<path>(.*))\" alt=\"(?<alt>(.*))\" />([\t\r\n ])*" +
                                  "</a>([\t\r\n ])*" +
                                "</div>");
      var match = regex.Match(str);

      var path = match.Groups["path"].Value;

      return match.Groups["path"].Value;
    }

    #region IImageProviderStrategy Members

    public ImageSource GetImage(DateTime date)
    {
      return HandleGetImage(date);
    }

    #endregion
  }
}
